package org.example.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;
@Component
public class ValidCodeFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        //只过滤login
        if("POST".equalsIgnoreCase(request.getMethod()) && "/login".equals(request.getServletPath())){
            String requestCode=request.getParameter("code");    //获取前端用户填写的验证码
            String validCode=(String) request.getSession().getAttribute("validcode");   //之前存的验证码
            if(!validCode.toLowerCase().equals(requestCode.toLowerCase())){ //如果验证码不相同
                request.getSession().setAttribute("msg","验证码错误");
                response.sendRedirect("/toLogin");  //跳转
            }
        }
        filterChain.doFilter(request,response); //正常放行
    }
}
